package solution;

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode cur = head;
        ListNode pre = null;

        int len = 0;
        while (cur != null) {
            len++;
            cur = cur.next;
        }

        cur = head;
        int count = 0;
        while (count < len - n) {
            pre = cur;
            cur = cur.next;
            count++;
        }

        if (pre != null) {
            pre.next = cur.next;
        } else {
            return head.next;
        }

        return head;
    }
}